package com.control;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.servlet.My;

import hyl.base.safe.MySm4;
import hyl.core.AIni;
import hyl.core.MyFun;
import hyl.core.info.Content;
import hyl.ext.base.MyToken;
import hyl.ext.base.SrcFactory;
import hyl.ext.base.C资源;

/**
 * 
 * 
 * 用户资源授权管理
 * 
 * 
 * 拥有者发布一个资源到redis库
 * 
 * 访问者通过密钥和令牌去获取资源
 * 
 * 
 * @author: zoudyaou qq:37798955
 * @date: 2018年11月20日 上午11:26:00
 * @copyright: 2018 zoudayou Inc. All rights reserved.
 *             注意：代码版权归邹达有所有，任何人未经授权不得私自用于商业目的
 */
@Controller("srcControl")
public class SrcControl {

	public SrcControl() {
	}

	@RequestMapping("/u/reqSrc")
	@ResponseBody
	public Content f请求资源(HttpServletRequest req, HttpServletResponse res, @RequestBody Map<String, String> R)
			throws ServletException, IOException {
		MyToken tk = My.getToken(req);
		String s = R.get("mm");// 电话
		if (MyFun.isEmpty(s)) {
			tk.msg.setCode(0, "请求异常!");
			return tk.msg;
		}
		s = MySm4.ecb解密16(tk.getSm4key(), s);

		if (MyFun.isEmpty(s)) {
			tk.msg.setCode(0, "请求异常!");
			return tk.msg;
		}
		String[] ss = s.split(",");
		String 资源令牌 = ss[0];
		String 资源密钥 = ss[1];
		if (MyFun.isEmpty(资源令牌)) {
			tk.msg.setCode(0, "资源的访问令牌不能为空!");
			return tk.msg;
		}
		if (MyFun.isEmpty(资源密钥)) {
			tk.msg.setCode(0, "资源的访问密钥不能为空!");
			return tk.msg;
		}
		C资源 sss = SrcFactory.getSrc(资源令牌, 资源密钥);
		if (sss == null) {
			tk.msg.setCode(0, "您访问资源不存在,请检查资源令牌和密码是否正确,或联系资源拥有者查询!");
			return tk.msg;
		}
		tk.msg.setCode(1, sss.src);
		return tk.msg;
	}

	@RequestMapping("/admin/regSrc")
	@ResponseBody
	public Content regMember(HttpServletRequest req, HttpServletResponse res, @RequestBody Map<String, String> R)
			throws ServletException, IOException {

		MyToken tk = My.getToken(req);
		String 用户信息 = R.get("mm");

		String str = MySm4.ecb解密16(tk.getSm4key(), 用户信息);
		if (MyFun.isEmpty(str)) {
			tk.msg.setCode(0, AIni.g消息("异常登录", tk.getLang()));
			return tk.msg;
		}
		// MyFun.print("用户名_密码",str);
		JSONObject jobj = JSON.parseObject(str);

		int 有效期_分钟 = jobj.getIntValue("有效期");
		String 资源 = jobj.getString("src");
		int 发布人 = jobj.getIntValue("user");
		String 密钥 = jobj.getString("pass");// 如果密钥不是十六进制字符,系统重新创建密钥
		// 判断是否已经发送过短信或者发送手机号码是否为空
		if (MyFun.isEmpty(资源) || 发布人 < 1) {
			tk.msg.setCode(0, AIni.g消息("表单必填项为空", tk.getLang()));
			return tk.msg;
		}
		// 判断发送短信的手机和验证码是否一致
		// 不能用验证码注册其他邮箱或手机
		C资源 ss = new C资源(有效期_分钟, 资源, 发布人, 密钥);
		SrcFactory.create资源(ss);
		tk.msg.setCode(1, ss.toJsonString());
		return tk.msg;
	}

}
